/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import { NewAppScreen } from '@react-native/new-app-screen';
import {
  StatusBar,
  StyleSheet,
  useColorScheme,
  View,
  Text,
  FlatList,
  Pressable,
} from 'react-native';
import {
  SafeAreaProvider,
  useSafeAreaInsets,
} from 'react-native-safe-area-context';

import { NativeModules, NativeEventEmitter } from 'react-native';
import { useEffect, useState } from 'react';

const { NiimbotModules } = NativeModules;

// 创建事件监听器
const niimbotEmitter = new NativeEventEmitter(NiimbotModules);

function App() {
  const isDarkMode = useColorScheme() === 'dark';

  return (
    <SafeAreaProvider>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      <AppContent />
    </SafeAreaProvider>
  );
}

function AppContent() {
  const [devices, setDevices] = useState([]); // 存储扫描到的打印机
  const [isScanning, setIsScanning] = useState(false);
  const safeAreaInsets = useSafeAreaInsets();

  useEffect(() => {
    // 监听扫描到的打印机
    const discoverListener = niimbotEmitter.addListener(
      'NiimbotDiscoverPeripheral',
      data => {
        console.log('发现打印机：', data);
        setDevices(prev => {
          // 避免重复添加
          if (prev.find(d => d.id === data.id)) {
            return prev;
          }
          return [...prev, data];
        });
      },
    );

    // 扫描结束
    const stopListener = niimbotEmitter.addListener('NiimbotStopScan', () => {
      console.log('扫描结束');
      setIsScanning(false);
    });

    return () => {
      discoverListener.remove();
      stopListener.remove();
    };
  }, []);

  const startScan = () => {
    setDevices([]);
    setIsScanning(true);
    NiimbotModules.startNiimbotScan({ seconds: 5 });
  };

  return (
    <View style={[styles.container, { paddingTop: safeAreaInsets.top }]}>
      <View style={styles.header}>
        <Pressable onPress={startScan} disabled={isScanning}>
          <Text
            style={[
              styles.button,
              { backgroundColor: isScanning ? '#aaa' : 'cyan' },
            ]}
          >
            {isScanning ? '扫描中...' : '开始扫描打印机'}
          </Text>
        </Pressable>
      </View>

      <FlatList
        data={devices}
        keyExtractor={item => item.id}
        renderItem={({ item }) => (
          <View style={styles.deviceItem}>
            <Text style={styles.deviceName}>{item.name}</Text>
            <Text style={styles.deviceId}>{item.id}</Text>
          </View>
        )}
        ListEmptyComponent={
          <View style={styles.empty}>
            <Text style={{ color: '#666' }}>
              {isScanning ? '正在扫描中...' : '未发现打印机'}
            </Text>
          </View>
        }
        contentContainerStyle={{ flexGrow: 1 }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    alignItems: 'center',
    padding: 16,
  },
  button: {
    color: 'black',
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 8,
    fontWeight: '600',
    textAlign: 'center',
  },
  deviceItem: {
    backgroundColor: 'white',
    marginHorizontal: 16,
    marginVertical: 8,
    padding: 12,
    borderRadius: 8,
    shadowColor: '#000',
    shadowOpacity: 0.05,
    shadowRadius: 3,
    shadowOffset: { width: 0, height: 1 },
  },
  deviceName: {
    fontSize: 16,
    fontWeight: '500',
  },
  deviceId: {
    fontSize: 13,
    color: '#888',
    marginTop: 2,
  },
  empty: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default App;
